package org.hawk.gwt.ppc;

import java.io.IOException;

import org.hawk.gwt.ppc.reflect.LangPreprocessor;
import org.hawk.gwt.ppc.reflect.ReflectionProcessingUnit;

/**
 * Creates configured environment for the internal usage.
 * 
 * @author alex.bereznevatiy@gmail.com
 */
public class Environment {
	private static Environment instance;

	private Environment() {
	}

	/**
	 * @return <i></i> singleton instance of {@link Environment}
	 */
	public static Environment getInstance() {
		if (instance == null) {
			instance = new Environment();
		}
		return instance;
	}

	private CmdArgs argsProcessor;

	/**
	 * @return {@link Configuration} for this {@link Environment}
	 */
	public Configuration getConfiguration() {
		if (argsProcessor == null) {
			this.argsProcessor = new CmdArgs(new String[0]);
		}
		return argsProcessor;
	}

	/**
	 * Configure current {@link Environment} using command line arguments.
	 * 
	 * @param argsProcessor
	 * @throws IOException
	 */
	void configure(CmdArgs argsProcessor) throws IOException {
		this.argsProcessor = argsProcessor;
		ProcessingUnitsManager.getInstance().configure();
		if (argsProcessor.get(Configuration.REFLECTION_PARAMETER) != null) {
			ProcessingUnitsManager.getInstance().addProcessingUnit(
					new ReflectionProcessingUnit());
			ProcessingUnitsManager.getInstance().addProcessingUnit(
					new LangPreprocessor());
		}
	}

	/**
	 * @return GWT compiller arguments to be pased to
	 *         {@link com.google.gwt.dev.Compiler#main(String[])};
	 */
	String[] getCompillerArguments() {
		return argsProcessor.getCompillerArguments();
	}

	/**
	 * @return list of GWT modules names to be compiled.
	 */
	String[] getModules() {
		return argsProcessor.getModules();
	}

	/**
	 * Releases all the resources that should be released after compilation.
	 */
	void dispose() {
		if (!argsProcessor.get(
				Configuration.KEEP_PREPROCESSED_SOURCES_PARAMETER, false)) {
			ProcessingUnitsManager.getInstance().dispose();
		}
	}
}
